package com.netwit.common.config;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class DynamicDataSourceAspect {

    @Before("@annotation(com.netwit.common.config.DBSource)")
    public void beforeSwitchDB(JoinPoint point) {
        // 当前访问的class
        Class<?> clazz = point.getTarget().getClass();
        // 当前访问的方法名
        String methodName = point.getSignature().getName();
        // 方法的参数类型
        Class<?>[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();

        String dataSource = DataSourceContextHolder.DEFAULT_DS;

        try {
            // 得到访问的方法对象
            Method method = clazz.getMethod(methodName, argClass);
            // 判断是否存在@DBSource注解
            if (method.isAnnotationPresent(DBSource.class)) {
                DBSource annotation = method.getAnnotation(DBSource.class);
                // 取出其中的数据源名称
                dataSource = annotation.value();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 切换数据源
        DataSourceContextHolder.setDb(dataSource);
    }

    @After("@annotation(com.netwit.common.config.DBSource)")
    public void afterSwithDB(JoinPoint point) {
        DataSourceContextHolder.clear();
    }

}